<?php
namespace control;
/*
*劳务名册类
*/

class laborClass extends adIndexClass
{
    private const page = 'labor';
    private const table = 'labor';
    private const title = '劳务名册';
    public array $stateOption = ['在派', '已退回'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'peopleListSearch':
                $tr = [
                    'name'      => [
                        'name'  => "姓名",
                        'width' => 100,
                    ],
                    'department' => [
                        'name'  => "部门",
                        'width' => 200,
                    ],
                    'job'  => [
                        'name'  => "职位",
                        'width' => 200,
                    ],
                    'idCard'         => [
                        'name'  => '身份证号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'sex'          => [
                        'name'  => '性别',
                        'width' => 100,
                    ],
                    'age'    => [
                        'name'  => '年龄',
                        'width' => 100,
                    ],
                    'tel'    => [
                        'name'  => '手机号',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'startDate'    => [
                        'name'  => '派遣日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'endDate'    => [
                        'name'  => '退回日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'state'    => [
                        'name'  => '状态',
                        'width' => 150,
                    ]
                ];
                break;
            default:
                $tr = [
                    'name'      => [
                        'name'  => "姓名",
                        'width' => 100,
                    ],
                    'department' => [
                        'name'  => "部门",
                        'width' => 150,
                    ],
                    'job'  => [
                        'name'  => "职位",
                        'width' => 100,
                    ],
                    'idCard'         => [
                        'name'  => '身份证号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'sex'          => [
                        'name'  => '性别',
                        'width' => 70,
                    ],
                    'age'    => [
                        'name'  => '年龄',
                        'width' => 70,
                    ],
                    'tel'    => [
                        'name'  => '手机号',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'startDate'    => [
                        'name'  => '派遣日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'endDate'    => [
                        'name'  => '退回日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'company'    => [
                        'name'  => '派遣单位',
                        'width' => 200,
                    ],
                    'orderNo'    => [
                        'name'  => '派遣协议编号',
                        'width' => 180,
                    ],
                    'state'    => [
                        'name'  => '状态',
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function peopleListOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "姓名"     => text(array("name" => "name")),
                    '部门'   => selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name']),
                    '职位'   => selectMultiple(["name" => "jobId", 'table' => " job", 'sqlId' => 'id', 'sqlField' => 'name']),
                ],
                [
                    "联系方式"     => text(array("name" => "tel")),
                    "身份证号"     => text(array("name" => "idCard")),
                    '派遣日期'   => text(array("name" => "startDate", 'laydate' => ['type' => 'date', 'range' => '~'])).
                        hidden(array('name' => 'id', 'value' => $this->get('id'))),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 派遣清单
     */
    public function peopleList(): bool|string
    {
        $html = $this->peopleListOptions(false);
        $id = $this->get('id');
        //控件
        $button = '';
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail";
        if ($this->power('laborAgreement', "edit")) {
            $button .= "<span class='spanButton' onclick=\"newIframe('劳务详情', '" . $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . suiji() . "&aid=$id')\">新增</span>\n";
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{})\" class='spanButton'>退回</span>\n";
            $button .=
                "<a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=downloadAgreement'><span class='spanButton'>导入模板</span></a>" .
                $this->upButton(array("title" => "导入", "fun" => "importAgreement"));
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportAgreement'><span class='spanButton'>导出</span></a>\n";

        }
        if ($this->power('laborAgreement', "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('laborAgreement', 'operate', {act: 'delMx', orderId: '$id'})\">删除</span>\n";
        }
        $json['html'] = $this->search($html,layout: 'pop',toolButton: $button);
        return json_encode($json, 320);
    }

    /**
     * 派遣清单
     * @return bool|string
     */
    public function peopleListSearch(): bool|string
    {
        $id = $this->post('id');
        //查询结果
        $where = " aid = '$id' ";
        $equal = [
            "a.jobId" => $this->post('jobId'),//职位
        ];
        $like = [
            'b.name' => $this->post('name'),
            'b.tel' => $this->post('tel'),
            "b.idCard" => $this->post('idCard'),//身份证号
        ];
        $and = '';
        if (!empty($this->post('departmentId'))) {
            //部门
            $and .= " and a.jobId in (select id from job where departmentId = '{$this->post('departmentId')}')";
        }
        if ($this->post('startDate')) {
            $and .= self::timeComparison($this->post('startDate'), field: 'a.startDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'a.startDate',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //生成查询语句
        $where .= search([
                "=" => $equal,
                "like" => $like,
            ]) . $and;
        $page = $this->page([
            "field" => "a.*,b.name,b.tel,b.birthDay,b.idCard,b.sex",
            "table" => 'labor_agreement_detail as a join ' . self::table . ' as b on a.laborId = b.id',
            "where" => $where,
            "order" => $orderBy['orderBy'],
        ]);
        //获取表头
        $_SESSION['laborAgreement']['sql'] = $page['fullSql'];
        $_SESSION['laborAgreement']['id'] = $id;
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("recordForm", "laborId")
        );
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail";
        $talentPool = new staffProfilesClass();
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = [
                "box" => [
                    "name" => "laborId",
                    "value" => $array['id']
                ],
                'edit' => ["title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&aid={$array['aid']}&id=" . $array['id'] . "')"],
            ];
            $liButton[] = $this->dominate($dominate);
            $job = query('job', " id = '$array[jobId]'");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "department":
                        $row[] = departmentClass::getTypeName($job['departmentId']);
                        break;
                    case "job":
                        $row[] = $job['name'];
                        break;
                    case "age":
                        $row[] = $talentPool->age($array['birthDay']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = '';
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //控件
        $json['html'] = $page['hint'] . $button . "<form name='recordForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 下载模板
     */
    public function downloadAgreement()
    {
        if (!$this->power('laborAgreement', 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        } else {
            $title = ['*姓名', '*性别', '*手机号', '*身份证号', '出生年月','邮箱',  '民族', '籍贯', '身高(cm)', '体重(kg)', '健康状况', '学历', '专业',
                '毕业院校', '参加工作时间', '职称','婚姻状况', '政治面貌', '户籍地址','户口性质', '通讯住址', '邮政编码','紧急联系人姓名', '与联系人关系','紧急联系人电话', '备注',
                '派遣日期','拟任职位','直属上级编号','直属上级名称','劳动报酬','工作备注'];
            $data[] = ['张三', '男', '13000000000', '500223199999999999', '1995-10-10','123456@qq.com', '汉族', '重庆市', '170', '60', '健康', '本科', '计算机', '重庆大学',
                '2012-01-01','', '未婚', '群众', '重庆市','非农户口', '重庆市', '123456','张五','父子', '13111111111', '无', '2022-01-01','销售专员','YM202207260001','李四','3000','测试'];
            $text = $this->control['name'] . "下载了派遣清单导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, '派遣清单导入模板.xlsx');
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }
    /*数据导入分析*/
    public function importAgreement()
    {
        $id = $_SESSION['laborAgreement']['id'];
        if (!$this->power('laborAgreement', 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        }elseif(empty($id)){
            $_SESSION['warn'] = '未找到派遣协议ID';
        } else {
            $talentObj = new talentPoolClass();
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $nationOption = explode('、', para('nationOption'));
            $educationOption = explode('，', para('education'));
            $jobOption = explode('，', para('jobTitleOption'));
            $polOption = explode('，', para('politicsStatus'));
            $healthOption = explode('，', para('healthOption'));
            $residenceTypeOption = $talentObj->residenceTypeOption;
            foreach ($data as $i => $row) {
                if ($i > 0) {
                    $cell = formSubArray($row);
                    //先判断劳工名册中是否已存在此人员
                    $labor = query('labor', " idCard = '$cell[4]'");
                    if (!empty($labor['id'])){
                        $field['id'] = $labor['id'];
                    }else{
                        $field = [
                            "id" => self::getId(),
                            'name' => $cell[0],
                            'sex' =>  $cell[1],
                            'tel' => $cell[2],
                            'idCard' => $cell[3],
                            'birthDay' => $cell[4],
                            'email' => $cell[5],
                            'nation' => $cell[6],
                            'homeTown' => $cell[7],
                            'height' =>  $cell[8],
                            'weight' =>  $cell[9],
                            'health' =>  $cell[10],
                            'education' => $cell[11],
                            'major' => $cell[12],
                            'college' => $cell[13],
                            'workDate' => $cell[14],
                            'jobTitle' =>  $cell[15],
                            'marriage' => $cell[16],
                            'politicsStatus' => $cell[17],
                            'residenceAddress' => $cell[18],
                            'residenceType'=>$cell[19],
                            'liveAddress' => $cell[20],
                            'postCode' => $cell[21],
                            'secContactName' => $cell[22],
                            'secContactRelation' => $cell[23],
                            'secContactTel' => $cell[24],
                            'text' =>$cell[25],
                        ];
                        $annotation = [
                            'name' => '姓名',
                            'sex' => '性别',
                            'tel' => '手机号',
                            'idCard' => '身份证号',
                        ];
                        $rules = [
                            'name' => 'required',
                            'sex' => 'required',
                            'tel' => 'required|tel',
                            'idCard' => 'required|id_card',
                        ];
                        // 校验是否符合规则
                        $vt = new \verify();
                        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                        if ($result === false) {
                            $text .= "第【{$i}】行：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                            continue;
                        } elseif(!in_array($field['sex'],['男','女'])){
                            $text .= "第【{$i}】行：性别不在可选项中<br>";
                            continue;
                        } elseif(!empty($field['nation']) && !in_array($field['nation'],$nationOption)){
                            $text .= "第【{$i}】行：民族不在可选项中<br>";
                            continue;
                        }  elseif(!empty($field['education']) && !in_array($field['education'],$educationOption)){
                            $text .= "第【{$i}】行：学历不在可选项中<br>";
                            continue;
                        }   elseif(!empty($field['politicsStatus']) && !in_array($field['politicsStatus'],$polOption)){
                            $text .= "第【{$i}】行：政治面貌不在可选项中<br>";
                            continue;
                        }  elseif(!empty($field['jobTitle']) && !in_array($field['jobTitle'],$jobOption)){
                            $text .= "第【{$i}】行：职称不在可选项中<br>";
                            continue;
                        }elseif(!empty($field['residenceType']) && !in_array($field['residenceType'],$residenceTypeOption)){
                            $text .= "第【{$i}】行：户口性质不在可选项中<br>";
                            continue;
                        }elseif(!empty($field['health']) && !in_array($field['health'],$healthOption)){
                            $text .= "第【{$i}】行：健康状况不在可选项中<br>";
                            continue;
                        } else {
                            $userNo = codeTemplateClass::generateCode(self::page,[
                                'prefix' => 'LW' . date('Ymd'),
                                'table' => self::table,
                                'field' => 'orderNo',
                                'where' => '',
                            ],$field);
                            $field['orderNo'] = $userNo;
                            $warn = insert(["table" => self::table, "field" => $field]);
                            if ($warn !='新增成功'){
                                $text .= "第【{$i}】行：新增劳务名册失败<br>";
                                continue;
                            }
                        }
                    }
                    $job = query('job',"name = '$cell[27]'");
                    $manager = query('staff',"orderNo = '$cell[28]'");
                    $cell[26] = self::importDateFormat($cell[26]);
                    $entryField = [
                        'startDate' => $cell[26],
                        'jobId' => $job['id'],
                        'managerId' => $manager['stid'],
                        'text' => $cell[31],
                        'salary' => $cell[30],
                    ];
                    $enAnnotation = [
                        'jobId' => '拟任职位',
                        'startDate' => '派遣日期',
                        'salary' => '劳动报酬',
                    ];
                    $enRules = [
                        'jobId' => 'required',
                        'startDate' => 'required',
                        'salary' => 'required',
                    ];
                    // 校验是否符合规则
                    $vt2 = new \verify();
                    $entryResult = $vt2->setAliases($enAnnotation)->validate($entryField, $enRules)->isOk();
                    if ($entryResult === false) {
                        $text .= "第【{$i}】行：" . $vt2->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                        continue;
                    }
                    /******判断当前派遣清单中是否已存在此劳工*******/
                    $labor_agreement_detail = query('labor_agreement_detail', " laborId = '$field[id]' and aid = '$id'");
                    if (empty($labor_agreement_detail['id'])) {
                        //没有派遣信息
                        $entryField = array_merge($entryField, [
                            'id' => suiji(),
                            'aid' => $id,
                            'laborId' => $field['id'],
                            'state' => '在派',
                        ]);
                        $warn = static::insert(array('table' => 'labor_agreement_detail', 'field' => $entryField));
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= "第【{$i}】行：导入成功<br>";
                        } else {
                            $text .= "第【{$i}】行：导入失败：编辑失败<br>".$warn;
                        }
                    } else {
                        $text .= "第【{$i}】行：导入失败：派遣清单中已存在此人员<br>";
                    }
                }
            }
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $warn = "成功导入" . $x . "条数据，详情请查看日志！";
            $_SESSION['warn'] = $warn;
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }


    /**
     * 导出
     */
    public function exportAgreement()
    {
        $id = $_SESSION['laborAgreement']['id'];
        if (!$this->power('laborAgreement', 'edit')) {
            $_SESSION['warn'] = '你还没有劳务派遣协议的编辑权限';
        } elseif (empty($id)) {
            $_SESSION['warn'] = '未找到派遣协议ID';
        } else {
            $data = [];
            $staffObj = new staffProfilesClass();
            $sql = $_SESSION['laborAgreement']['sql'];
            $title = ['协议编号', '协议名称', '派遣单位', '姓名', '部门', '职位', '身份证号', '性别', '年龄', '手机号', '派遣日期', '退回日期', '状态'];
            $result = sqlFind($sql);
            if (is_array($result)) {
                foreach ($result as $array) {
                    $job = query('job', " id = '$array[jobId]'");
                    $laborAgreement = query('labor_agreement', "id = '$array[aid]'");
                    $comapny = query('labor_company', "id = '$laborAgreement[companyId]'");
                    $data[] = [$laborAgreement['orderNo'], $laborAgreement['name'], $comapny['name'], $array['name'], departmentClass::getTypeName($job['departmentId']), $job['name'], $array['idCard'], $array['sex'], $staffObj->age($array['birthDay']), $array['tel'], $array['startDate'], $array['endDate'], $array['state']];
                }
            }
            $text = $this->control['name'] . "导出了派遣清单";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "派遣清单.xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    /**
     * 退回
     */
    public function stateSwitch(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "退回日期：" => text(array('name' => 'endDate', 'laydate' => [], 'value' => $this->date)),
            ),
            array(
                "退回原因" => text(array('name' => 'endText', 'class' => 'long'))
            )
        )));
        //返回
        return $this->layer(array("title" => "退回", "height" => 250, "width" => 800, "html" => $html, 'formTwo' => 'recordForm'));
    }

    /**
     *退回
     */
    public function stateSwitchEdit(): bool|string
    {
        $idArr = $this->post('laborId');
        $field = [
            'endDate' => $this->post('endDate'),
            'endText' => $this->post('endText'),
            'state' => '已退回'
        ];
        if (!$this->power('laborAgreement', "edit")) {
            $json['warn'] = "你没有派遣协议的编辑权限";
        } elseif (static::is_null_array($idArr)) {
            $json['warn'] = "请选择数据";
        } elseif (empty($field['endDate'])) {
            $json['warn'] = '请选择退回日期';
        } else {
            $x = 0;
            foreach ($idArr as $id) {
                $info = query('labor_agreement_detail', "id = '$id'");
                $labor = query(self::table, "id = '$info[laborId]'");
                if ($info['state'] != '在派') {
                    $text = $this->control['name'] . "退回【{$labor['name']}】失败，状态不是在派";
                } elseif (strtotime($field['endDate']) < strtotime($info['startDate'])) {
                    $text = $this->control['name'] . "退回【{$labor['name']}】失败，退回日期不能小于派遣日期";
                } else {
                    $warn = update(array('table' => 'labor_agreement_detail', 'field' => $field, 'where' => " id = '$id'"));
                    if ($warn == '更新成功') {
                        $x++;
                        $text = $this->control['name'] . "退回【{$labor['name']}】成功";
                    } else {
                        $text = $this->control['name'] . "退回【{$labor['name']}】失败";
                    }
                }
                $this->logText(["type" => 'laborAgreement', "text" => $text]);
            }
            $_SESSION['warn'] = "成功退回了{$x}个劳务人员";
            $json['href'] = root . 'control/adIndex.html?cla=laborAgreement&fun=detail&menu=peopleList&id=' . ($info['aid'] ?? '');
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "状态" => checkbox(array(
                        "name" => "state",
                        "value" => $this->stateOption,
                        "checked" => array("在派"),
                    )),
                ],
                [
                    "姓名"     => text(array("name" => "name")),
                    '部门'   => selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name']),
                    '职位'   => selectMultiple(["name" => "jobId", 'table' => " job", 'sqlId' => 'id', 'sqlField' => 'name']),
                ],
                [
                    "性别" => select(array("name" => "sex", "option" => ['男', '女'])),
                    "联系方式"     => text(array("name" => "tel")),
                    "身份证号"     => text(array("name" => "idCard")),
                ],
                [
                    '派遣单位'   => selectMultiple(["name" => "companyId", 'sqlId' => 'id', 'sqlField' => 'name', 'table' => 'labor_company', 'where' => "state = '启用' order by orderNo"]),
                    "派遣协议编号"     => text(array("name" => "orderNo")),
                    '派遣日期'   => text(array("name" => "startDate", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','back',{})\" class='spanButton'>退回</span>\n";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "a.name" => $this->post('name'),//姓名
            "a.tel" => $this->post('tel'),//手机号
            "a.idCard" => $this->post('idCard'),//身份证号
        );
        //全等查询数组
        $equal = array(
            "b.jobId" => $this->post('jobId'),//职位
            "a.sex" => $this->post('sex'),//性别
        );
        $and = "";
        if (!empty($this->post('departmentId'))) {
            //部门
            $and .= " and b.jobId in (select id from job where departmentId = '{$this->post('departmentId')}')";
        }
        if ($this->post('startDate')) {
            $and .= self::timeComparison($this->post('startDate'), field: 'b.startDate');
        }
        if (!empty($this->post('state'))) {
            $and .= " and b.state in ('" . implode("','", $this->post('state')) . "') ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'b.startDate',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            'field'=>"a.*,b.startDate,b.endDate,b.aid,b.state,b.jobId",
            "table" =>  self::table . " as a join (select laborId,any_value(t.startDate) as startDate,any_value(t.state) as state,any_value(t.jobId) as jobId,any_value(t.endDate) as endDate,any_value(t.aid) as aid from (select * from labor_agreement_detail order by startDate desc) as t group by t.laborId) as b on a.id = b.laborId",
            "where" => $where,
            "order" => $orderBy['orderBy'],
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        $talentPool = new staffProfilesClass();
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                'edit' => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => "劳务详情", "click" => "newIframe('劳务详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            $job = query('job', " id = '$array[jobId]'");
            $agreement = query('labor_agreement', " id = '$array[aid]'");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "department":
                        $row[] = departmentClass::getTypeName($job['departmentId']);
                        break;
                    case "job":
                        $row[] = $job['name'];
                        break;
                    case "age":
                        $row[] = $talentPool->age($array['birthDay']);
                        break;
                    case "company":
                        $company = query('labor_company', " id = '$agreement[companyId]'");
                        $row[] = $company['name'];
                        break;
                    case "orderNo":
                        $row[] = $agreement['orderNo'];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    public function back(){
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "退回日期：" => text(array('name' => 'endDate', 'laydate' => [], 'value' => $this->date)),
            ),
            array(
                "退回原因" => text(array('name' => 'endText', 'class' => 'long'))
            )
        )));
        //返回
        return $this->layer(array("title" => "退回", "height" => 250, "width" => 800, "html" => $html, 'formTwo' => 'listForm'));
    }

    public function backEdit(){
        $idArr = $this->post('listId');
        $field = [
            'endDate' => $this->post('endDate'),
            'endText' => $this->post('endText'),
            'state' => '已退回'
        ];
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有劳务名册的编辑权限";
        } elseif (static::is_null_array($idArr)) {
            $json['warn'] = "请选择数据";
        } elseif (empty($field['endDate'])) {
            $json['warn'] = '请选择退回日期';
        } else {
            $x = 0;
            foreach ($idArr as $id) {
                $labor = query(self::table, "id = '$id'");
                $info = query('labor_agreement_detail', "laborId = '$id' order by time desc");
                if ($info['state'] != '在派') {
                    $text = $this->control['name'] . "退回【{$labor['name']}】失败，状态不是在派";
                } elseif (strtotime($field['endDate']) < strtotime($info['startDate'])) {
                    $text = $this->control['name'] . "退回【{$labor['name']}】失败，退回日期不能小于派遣日期";
                } else {
                    $warn = update(array('table' => 'labor_agreement_detail', 'field' => $field, 'where' => " id = '$info[id]'"));
                    if ($warn == '更新成功') {
                        $x++;
                        $text = $this->control['name'] . "退回【{$labor['name']}】成功";
                    } else {
                        $text = $this->control['name'] . "退回【{$labor['name']}】失败";
                    }
                }
                $this->logText(["type" => 'laborAgreement', "text" => $text]);
            }
            $_SESSION['warn'] = "成功退回了{$x}个劳务人员";
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $data = [];
            $talentPool = new staffProfilesClass();
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    'field'=>"a.*,b.startDate,b.endDate,b.aid,b.state,b.jobId",
                    "table" =>  self::table . " as a join (select laborId,any_value(t.startDate) as startDate,any_value(t.state) as state,any_value(t.jobId) as jobId,any_value(t.endDate) as endDate,any_value(t.aid) as aid from (select * from labor_agreement_detail order by startDate desc) as t group by t.laborId) as b on a.id = b.laborId",
                    "where" => "a.id in ('".implode("','", $checkedId)."') order by b.startDate desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $job = query('job', " id = '$array[jobId]'");
                $agreement = query('labor_agreement', " id = '$array[aid]'");
                $company = query('labor_company', " id = '$agreement[companyId]'");
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '姓名'=>$array['name'],
                            '部门'=>departmentClass::getTypeName($job['departmentId']),
                            '职位'=>$job['name'],
                            '身份证号'=>$array['idCard'],
                            '性别'=>$array['sex'],
                            '年龄'=>$talentPool->age($array['birthDay']),
                            '手机号'=>$array['tel'],
                            '派遣日期'=>$array['startDate'],
                            '退回日期'=>$array['endDate'],
                            '派遣单位'=> $company['name'],
                            '派遣协议编号'=>$agreement['orderNo'],
                            '状态'=>$array['state'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了劳务名册表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "劳务名册表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }


    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        if ($this->get('aid')) {
            //派遣清单入口
            $labor_agreement_detail = query('labor_agreement_detail', " id = '" . $this->get('id') . "' order by time desc");
            $info = query(self::table, " id = '" . $labor_agreement_detail['laborId'] . "' ");
            $labor_agreement = query('labor_agreement', " id = '" . $this->get('aid') . "' ");
        } else {
            $info = query(self::table, " id = '" . $this->get('id') . "' ");
            $labor_agreement_detail = query('labor_agreement_detail', " laborId = '" . $info['id'] . "' order by time desc");
            $labor_agreement = query('labor_agreement', " id = '" . $labor_agreement_detail['aid'] . "' ");
        }
        $id = $info['id'] ?: suiji();
        $company = query('labor_company', "id = '$labor_agreement[companyId]'");
        //引入人才库对象
        $talentObj = new talentPoolClass();
        /*****学习经历*********/
        $educationTr[] = ['', '学习(培训)起止日期', '毕业院校(培训单位)', '所学专业(相关培训)', '获得证书(成果)'];
        $result = find(array(
            'field' => "id as studyId,studyDate as educationDate,college as school,major as schoolMajor,certificate",
            'table' => "study_history where talentId = '{$id}' order by list asc"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['list'] = $k+1;
                $educationTr[] = $talentObj->educationRow($array);
            }
        }else{
            $educationTr[] = $talentObj->educationRow(['studyId'=>self::getId(), 'list'=>1]);
        }

        /*****工作经历*********/
        $workTr[] = ['', '工作起止日期', '就职单位', '岗位', '工作内容', '离职原因'];
        $result = find(array(
            'field' => "id as workId,workDate,companyName,position,content,cause",
            'table' => "job_history where talentId = '{$id}' order by list asc"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['list'] = $k+1;
                $workTr[] = $talentObj->workRow($array);
            }
        }else{
            $workTr[] = $talentObj->workRow(['workId'=>self::getId(), 'list'=>1]);
        }

        /*****家庭成员*********/
        $familyTr[] = ['', '姓名', '关系', '工作单位', '联系电话'];
        $result = find(array(
            'field' => "id as familyId,name as memberName,relation,company as memberCompany,contactTel",
            'table' => "talent_family where talentId = '{$id}' order by list asc"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['list'] = $k+1;
                $familyTr[] = $talentObj->familyRow($array);
            }
        }else{
            $familyTr[] = $talentObj->familyRow(['familyId'=>self::getId(), 'list'=>1]);
        }
        $button = $photo = [];
        if ($this->power(self::page, "edit")) {
            //按钮
            $button[] = [
                "name" => "保存",
                "type" => "点击事件",
                "cla" => $this->get('cla'),
                "fun" => "subForm('" . self::page . "EditForm',root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
                "post" => ["id" => $this->get('id')],
                'style' => 'li-btn-blue-bg',
            ];

            $ico = [];
            $all = find(array('table' => 'file', 'where' => "targetId = '$info[id]' and target in ('身份证正面','身份证背面','毕业证','学位证','银行卡','派遣单位劳动合同','体检报告','职称证书')"));
            foreach ($all['array'] as $array) {
                $ico[$array['target']] = $array['src'];
            }
            $photo = array(
                array("title" => "身份证正面", 'type' => '身份证正面', "url" => $ico['身份证正面'] ?? '', "id" => $id),
                array("title" => "身份证背面", 'type' => '身份证背面', "url" => $ico['身份证背面'] ?? '', "id" => $id),
                array("title" => "毕业证", 'type' => '毕业证', "url" => $ico['毕业证'] ?? '', "id" => $id),
                array("title" => "学位证", 'type' => '学位证', "url" => $ico['学位证'] ?? '', "id" => $id),
                array("title" => "银行卡", 'type' => '银行卡', "url" => $ico['银行卡'] ?? '', "id" => $id),
                array("title" => "派遣单位劳动合同", 'type' => '派遣单位劳动合同', "url" => $ico['派遣单位劳动合同'] ?? '', "id" => $id),
                array("title" => "体检报告", 'type' => '体检报告', "url" => $ico['体检报告'] ?? '', "id" => $id),
                array("title" => "职称证书", 'type' => '职称证书', "url" => $ico['职称证书'] ?? '', "id" => $id),
            );
        }
        $job = query('job', "id = '$labor_agreement_detail[jobId]'");
        $departmentName = departmentClass::getTypeName($job['departmentId']);
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '详细信息' => [
                [
                    must . "姓名：" => text(["name" => "name", "value" => $info['name']]),
                    must . "性别：" => radio(["name" => "sex", 'value' => ['男', '女'], "checked" => $info['sex'] ?: '男']),
                    must . "手机号码：" => text(["name" => "tel", "value" => $info['tel']]),
                    "邮箱：" => text(["name" => "email", "value" => $info['email']]),
                ],

                [
                    must . "身份证号：" => text(["name" => "idCard", 'blur' => 'getBirthDay', "value" => $info['idCard']]),
                    "民族：" => select(array('name' => 'nation', 'title' => '民族', 'class' => 'select', 'value' => $info['nation'], 'option' => explode('、', para('nationOption')))),
                    "籍贯：" => repeatSelect(array('name' => 'homeTown', 'title' => '籍贯', 'sqlForm' => 'region', 'sqlField' => 'province', 'value' => $info['homeTown'])),
                    '职称：' => select(array('name' => 'jobTitle', 'title' => '请选择', 'class' => 'select', 'value' => $info['jobTitle'], 'option' => explode('，', para('jobTitleOption')))),
                ],
                [
                    "学历：" => select(array('name' => 'education', 'title' => '学历', 'class' => 'select', 'value' => $info['education'], 'option' => explode('，', para('education')))),
                    "专业：" => text(["name" => "major", "value" => $info['major']]),
                    "毕业院校：" => text(["name" => "college", "value" => $info['college']]),
                    "参加工作时间：" => text(["name" => "workInDate", 'laydate' => ['type'=>'year'], "unit" => '年', "value" => $info['workDate']]),
                ],
                [
                    "婚姻状况：" => radio(["name" => "marriage", 'value' => $talentObj->marryOption, "checked" => $info['marriage']]),
                    "政治面貌：" => select(array('name' => 'politicsStatus', 'title' => '政治面貌', 'class' => 'select', 'value' => $info['politicsStatus'], 'option' => explode('，', para('politicsStatus')))),
                    "户籍地址：" => text(["name" => "residenceAddress", "value" => $info['residenceAddress']]),
                    "户口性质：" => radio(["name" => "residenceType", 'value' => $talentObj->residenceTypeOption, "checked" => $info['residenceType']]),
                ],
                [
                    "通讯住址：" => text(["name" => "liveAddress", "value" => $info['liveAddress']]),
                    "邮政编码：" => text(["name" => "postCode", "value" => $info['postCode']]),
                    "健康状况：" => select(array('name' => 'health', 'title' => '健康状况', 'class' => 'select', 'value' => $info['health'], 'option' => explode('，', para('healthOption')))),
                    "身高：" => text(["name" => "height", 'unit' => 'cm', "value" => $info['height'] > 0 ? $info['height'] : '']),
                ],
                [
                    "体重：" => text(["name" => "weight", 'unit' => 'kg', "value" => $info['weight'] > 0 ? $info['weight'] : '']),
                    "紧急联系人姓名：" => text(["name" => "secContactName", "value" => $info['secContactName']]),
                    "与紧急联系人关系：" => text(["name" => "secContactRelation", "value" => $info['secContactRelation']]),
                    "紧急联系人手机号：" => text(["name" => "secContactTel", "value" => $info['secContactTel']]),
                ],
                [
                    "备注：" => textarea(["name" => "text", "value" => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'title' => '学习经历',
            'html' => $this->listTable(array('tr' => $educationTr, 'end' => true)),
        ]);
        $body .= $this->editList([
            'title' => '工作经历',
            'html' => $this->listTable(array('tr' => $workTr, 'end' => true)),
        ]);
        $body .= $this->editList([
            'title' => '家庭成员',
            'html' => $this->listTable(array('tr' => $familyTr, 'end' => true)),
        ]);
        $body .= $this->edit4([
            '工作信息' => [
                [
                    must . "派遣日期：" => text(["name" => "startDate", 'laydate' => [], "value" => $labor_agreement_detail['startDate']]),
                    must . "派遣单位：" => $company['name'],
                    must . "派遣协议编号：" => $labor_agreement['orderNo'],
                    must . "劳动报酬：" => text(["name" => "workSalary", "value" => $labor_agreement_detail['salary']]),
                ],
                [
                    must . "拟任职位：" => selectMultiple([
                        "name" => "jobId", "title" => "请选择",
                        'value' => $labor_agreement_detail['jobId'],
                        'sqlField' => 'name',
                        'sqlId' => 'id',
                        'table' => "job",
                        'where' => "1=1 order by list",
                        'change' => 'getJobInfo'
                    ]),
                    '职位类型：' => "<span id='jobType'>{$job['type']}</span>",
                    '所属部门：' => "<span id='department'>{$departmentName}</span>",
                    "直属上级：" => selectMultiple([
                        "name" => "managerId", "title" => "直属上级",
                        'value' => $labor_agreement_detail['managerId'],
                        'sqlField' => 'name',
                        'sqlId' => 'stid',
                        'table' => "staff",
                    ]),
                ],
                [
                    "工作备注：" => textarea(["name" => "workText", "value" => $labor_agreement_detail['text']]),
                ],
            ],
            '个人资料' => [
                [
                    $talentObj->photo($photo)
                ],
            ],
            '附件' => [
                [
                    fileUploadClass::addFileComponent($id, '劳务名册', self::page, self::page . 'EditForm'),
                ],
            ]
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(array('name' => 'id', 'value' => $id)) . hidden(array('name' => 'aid', 'value' => $labor_agreement['id'])) . hidden(array('name' => 'detailId', 'value' => $labor_agreement_detail['id'])) . "<div class='hidden'><input name=\"type\" type=\"hidden\" ><input name='imgFile' accept=\"image/*\" id='imgFile' type='file' onchange=\"uploadImgFile('{$this->get('cla')}EditForm',root+'control/adIndex.html?cla=labor&fun=uploadIco')\"></div>",
        ]);
        $data['html'] .= $talentObj->editJs();
        //返回
        return $this->tab($data);
    }


    /**
     *信息保存
     */
    public function editEdit()
    {
        $id = $this->post('id');
//        $labor = query('labor', " id = '$id'");
        $field = [
            'email' => $this->post('email'),
            'name' => $this->post('name'),
            'sex' => $this->post('sex'),
            'tel' => $this->post('tel'),
            'idCard' => $this->post('idCard'),
            'birthDay' => $this->post('idCard')?self::getBirthdayFromIDCard($this->post('idCard')):'',
            'nation' => $this->post('nation'),
            'homeTown' => $this->post('homeTown'),
            'height' => $this->post('height'),
            'weight' => $this->post('weight'),
            'health' => $this->post('health'),
            'education' => $this->post('education'),
            'major' => $this->post('major'),
            'college' => $this->post('college'),
            'workDate' => $this->post('workInDate'),
            'marriage' => $this->post('marriage'),
            'politicsStatus' => $this->post('politicsStatus'),
            'residenceAddress' => $this->post('residenceAddress'),
            'residenceType' => $this->post('residenceType'),
            'liveAddress' => $this->post('liveAddress'),
            'secContactName' => $this->post('secContactName'),
            'secContactTel' => $this->post('secContactTel'),
            'secContactRelation' => $this->post('secContactRelation'),
            'jobTitle' => $this->post('jobTitle'),
            'text' => $this->post('text'),
            'postCode' => $this->post('postCode')
        ];
        $annotation = [
            'name' => '姓名',
            'sex' => '性别',
            'tel' => '手机号',
            'idCard' => '身份证号',
        ];
        $rules = [
            'name' => 'required',
            'sex' => 'required',
            'tel' => 'required|tel',
            'idCard' => 'required|id_card',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }

        $entryField = [
            'jobId' => $this->post('jobId'),
            'managerId' => $this->post('managerId'),
            'startDate' => $this->post('startDate'),
            'text' => $this->post('workText'),
            'salary' => $this->post('workSalary'),
        ];
        $enAnnotation = [
            'jobId' => '拟任职位',
            'startDate' => '派遣日期',
            'salary' => '劳动报酬',
        ];
        $enRules = [
            'jobId' => 'required',
            'startDate' => 'required',
            'salary' => 'required',
        ];
        // 校验是否符合规则
        $entryResult = $vt->setAliases($enAnnotation)->validate($entryField, $enRules)->isOk();
        if ($entryResult === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //学习经历
        $studyIdArr = $this->post('studyId') ?? [];
        $educationDateArr = $this->post('educationDate');
        $schoolArr = $this->post('school');
        $schoolMajorArr = $this->post('schoolMajor');
        $certificateArr = $this->post('certificate');
        //工作经历
        $workIdArr = $this->post('workId') ?? [];
        $workDateArr = $this->post('workDate');
        $companyNameArr = $this->post('companyName');
        $positionArr = $this->post('position');
        $contentArr = $this->post('content');
        $causeArr = $this->post('cause');
        //家庭成员
        $familyIdArr = $this->post('familyId') ?? [];
        $memberNameArr = $this->post('memberName');
        $relationArr = $this->post('relation');
        $memberCompanyArr = $this->post('memberCompany');
        $contactTelArr = $this->post('contactTel');
        //附件
        $fileIdArr = $this->post('fileId');

        $laborAgreementId = $this->post('aid');//协议ID
        $laborAgreementMxId = $this->post('detailId') ?: suiji();//派遣清单ID
        $info = query(self::table, "id = '$id'");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (!preg_match("/^([\x{4e00}-\x{9fa5}]+)$/u", $field['name']) && !preg_match("/^[a-z]+$/i", $field['name'])) {
            $json['warn'] = '姓名只能使用中文或英文';
        } elseif (!empty($field['email']) && preg_match(checkEmail, $field['email']) == 0) {
            $json['warn'] = '邮箱格式错误';
        } elseif (!empty($field['idCard']) && (static::total(array('sql' => "SELECT count(*) AS total FROM " . self::table . " where idCard = '{$field['idCard']}' and id !='$id'")))) {
            $json['warn'] = '已存在此身份证号的人员';
        } elseif (empty($laborAgreementId)) {
            $json['warn'] = '为找到此劳务人员的派遣协议';
        } else {
            $this->startTrans();//开启事务
            //劳务人员
            if (empty($info['id'])) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'LW' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge(
                    $field,
                    [
                        'id' => $id,
                        'orderNo' => $userNo,
                    ]
                );
                $json['warn'] = static::insert([
                    "table" => self::table,
                    "field" => $field,
                ]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => "id = '$id'"
                ]);
            }

            /******派遣信息*******/
            $labor_agreement_detail = query('labor_agreement_detail', " id = '$laborAgreementMxId'");
            if (empty($labor_agreement_detail['id'])) {
                //没有派遣信息
                $entryField = array_merge($entryField, [
                    'id' => $laborAgreementMxId,
                    'aid' => $laborAgreementId,
                    'laborId' => $id,
                    'state' => '在派',
                ]);
                $warn = static::insert(array('table' => 'labor_agreement_detail', 'field' => $entryField));

            } else {
                $warn = static::update(array('table' => 'labor_agreement_detail', 'field' => $entryField, 'where' => "id = '$laborAgreementMxId'"));
            }
            if (!in_array($warn, ['新增成功', '更新成功'])) {
                $json['warn'] = '添加入派遣记录失败';
            }

            //添加或更新学习经历
            if (is_array($studyIdArr)) {
                foreach ($studyIdArr as $k => $nid) {
                    if (static::total(array('table' => 'study_history', 'where' => " and id = '$nid'")) > 0) {
                        //更新
                        $warn = static::update([
                            "table" => 'study_history',
                            "field" => [
                                'studyDate' => $educationDateArr[$k],
                                'college' => $schoolArr[$k],
                                'major' => $schoolMajorArr[$k],
                                'certificate' => $certificateArr[$k],
                            ],
                            "where" => " id = '$nid'"
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => 'study_history',
                            "field" => [
                                'id' => $nid,
                                'talentId' => $id,
                                'studyDate' => $educationDateArr[$k],
                                'college' => $schoolArr[$k],
                                'major' => $schoolMajorArr[$k],
                                'certificate' => $certificateArr[$k],
                                'time' => $this->time
                            ],
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            //添加或更新工作经历
            if (is_array($workIdArr)) {
                foreach ($workIdArr as $k => $nid) {
                    if (static::total(array('table' => 'job_history', 'where' => " and id = '$nid'")) > 0) {
                        //更新
                        $warn = static::update([
                            "table" => 'job_history',
                            "field" => [
                                'companyName' => $companyNameArr[$k],
                                'position' => $positionArr[$k],
                                'content' => $contentArr[$k],
                                'cause' => $causeArr[$k],
                                'workDate' => $workDateArr[$k],
                            ],
                            "where" => " id = '$nid'"
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => 'job_history',
                            "field" => [
                                'id' => $nid,
                                'talentId' => $id,
                                'companyName' => $companyNameArr[$k],
                                'position' => $positionArr[$k],
                                'content' => $contentArr[$k],
                                'cause' => $causeArr[$k],
                                'workDate' => $workDateArr[$k],
                                'time' => $this->time
                            ],
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            //添加或更新家庭成员
            if (is_array($familyIdArr)) {
                foreach ($familyIdArr as $k => $nid) {
                    if (static::total(array('table' => 'talent_family', 'where' => " and id = '$nid'")) > 0) {
                        //更新
                        $warn = static::update([
                            "table" => 'talent_family',
                            "field" => [
                                'name' => $memberNameArr[$k],
                                'relation' => $relationArr[$k],
                                'company' => $memberCompanyArr[$k],
                                'contactTel' => $contactTelArr[$k],
                            ],
                            "where" => " id = '$nid'"
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => 'talent_family',
                            "field" => [
                                'id' => $nid,
                                'talentId' => $id,
                                'name' => $memberNameArr[$k],
                                'relation' => $relationArr[$k],
                                'company' => $memberCompanyArr[$k],
                                'contactTel' => $contactTelArr[$k],
                                'time' => $this->time
                            ],
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            //添加主表ID到附件表
            if (is_array($fileIdArr)) {
                $warn = update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                if ($warn != '更新成功') {
                    $json['warn'] = '文件上传失败';
                }
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();//提交事务
                //删除不在此ID中的数据
                delete(array('table' => 'talent_family', 'where' => " id not in ('" . implode("','", $familyIdArr) . "') and talentId = '$info[id]'"));
                delete(array('table' => 'job_history', 'where' => " id not in ('" . implode("','", $workIdArr) . "') and talentId = '$info[id]'"));
                delete(array('table' => 'study_history', 'where' => " id not in ('" . implode("','", $studyIdArr) . "') and talentId = '$info[id]'"));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $info['id'] . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();//回滚
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            $talentObj = new talentPoolClass();
            $staffObj = new staffProfilesClass();
            //派遣信息
            $labor_agreement_detail = query('labor_agreement_detail', " laborId = '$info[id]' order by time desc");
            //菜单
            $data = array(
                "id" => $info['id'],
                'menu' => [
                    "detail" => "基本信息",
                ]
            );
            $button = [];
            if ($this->power(self::page, "edit")) {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "顶部页卡",
                    "title" => "劳务详情",
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $info['id'],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($this->power(self::page, 'del')) {
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => 'laborAgreement',
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }


            $ico = [];
            $all = find(array('table' => 'file', 'where' => "targetId = '$info[id]' and target in ('身份证正面','身份证背面','毕业证','学位证','银行卡','离职证明','体检报告','职称证书')"));
            foreach ($all['array'] as $array) {
                $ico[$array['target']] = $array['src'];
            }
            $photo = array(
                array("title" => "身份证正面", 'type' => '身份证正面', "url" => $ico['身份证正面'] ?? ''),
                array("title" => "身份证背面", 'type' => '身份证背面', "url" => $ico['身份证背面'] ?? ''),
                array("title" => "毕业证", 'type' => '毕业证', "url" => $ico['毕业证'] ?? ''),
                array("title" => "学位证", 'type' => '学位证', "url" => $ico['学位证'] ?? ''),
                array("title" => "银行卡", 'type' => '银行卡', "url" => $ico['银行卡'] ?? ''),
                array("title" => "离职证明", 'type' => '离职证明', "url" => $ico['离职证明'] ?? ''),
                array("title" => "体检报告", 'type' => '体检报告', "url" => $ico['体检报告'] ?? ''),
                array("title" => "职称证书", 'type' => '职称证书', "url" => $ico['职称证书'] ?? ''),
            );
            /*******附件****************/
            $fileCollection = fileUploadClass::showFile($info['id'], '劳务名册');
            //职位
            $job = query('job', " id = '$labor_agreement_detail[jobId]'");
            //派遣协议
            $labor_agreement = query('labor_agreement', " id = '$labor_agreement_detail[aid]'");
            $company = query('labor_company', "id = '$labor_agreement[companyId]'");
            //生成表单
            $staffObj = new staffProfilesClass();
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '基本信息' => array(
                    array(
                        "姓名" => $info['name'],
                        "性别" => $info['sex'],
                        "手机号" => $info['tel'],
                        "邮箱" => $info['email'],
                    ),
                    array(
                        "身份证号" => $info['idCard'],
                        "出生年月" => $info['birthDay'] .'（'.$staffObj->age($info['birthDay']) . '岁）',
                        "民族" => $info['nation'],
                        "籍贯" => $info['homeTown'],
                    ),
                ),
                "详细信息" => array(
                    array(
                        "职称" => $info['jobTitle'],
                        "学历" => $info['education'],
                        "专业" => $info['major'],
                        "毕业院校" => $info['college'],
                    ),
                    array(
                        "参加工作时间" => $info['workDate'] . '年' .'（已工作'. (date("Y")-(int)$info['workDate']) . '年）',
                        "婚姻状况" => $info['marriage'],
                        "政治面貌" => $info['marriage'],
                        "户籍地址" => $info['residenceAddress'],
                    ),
                    array(
                        "户口性质" => $info['residenceType'],
                        "通讯住址" => $info['liveAddress'],
                        "邮政编码" => $info['postCode'],
                    ),
                    array(
                        "健康状态" => $info['health'],
                        "身高" => $info['height'] . 'cm',
                        "体重" => $info['weight'] . 'kg',
                    ),
                    array(
                        "紧急联系人姓名" => $info['secContactName'],
                        "紧急联系人关系" => $info['secContactRelation'],
                        "紧急联系人电话" => $info['secContactTel'],
                    ),
                    array(
                        "备注" => pre($info['text']),
                    ),
                ),
                "派遣信息" => array(
                    array(
                        "部门" => departmentClass::getTypeName($job['departmentId']),
                        "职位" => $job['name'],
                        "职位类型" => $job['type'],
                        "直属上级" => self::findStaff($labor_agreement_detail['managerId']),
                    ),
                    array(
                        "派遣日期" => $labor_agreement_detail['startDate'],
                        "退回日期" => self::null($labor_agreement_detail['endDate']),
                        '退回原因' => $labor_agreement_detail['endText'],
                        "派遣单位" => $company['name'],
                    ),
                    array(
                        "派遣协议编号" => $labor_agreement['orderNo'],
                        "协议签订日期" => self::null($labor_agreement['signDate']),
                        "协议起止日期" => self::null($labor_agreement['startDate']) . '至' . self::null($labor_agreement['endDate']),
                    ),
                    array(
                        "劳动报酬" => $labor_agreement_detail['salary'],
                        '工作备注' => $labor_agreement_detail['text'],
                        '状态' => $labor_agreement_detail['state']
                    ),
                ),
                "个人资料" => array(
                    array(
                        $talentObj->photo($photo)
                    )
                ),
                "附件" => array(
                    array(
                        $fileCollection
                    ),
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    /**
     * @param $data
     * @return string
     */
    public function photo($data): string
    {
        $li = "";
        foreach ($data as $num => $array) {
            //编辑表单
            $click = '';
            if (!empty($array['id'])) {
                $click = "<img  src='" . root . "img/images/clickEdit.png' onClick=\"clickUpload('{$array['id']}','{$array['type']}')\" class='clickIco'>";
            }
            //点击显示大图功能
            if (empty($array['url'])) {
                $img = "<img class='smallImg imgHover' data-type='{$array['type']}' src='" . root . "img/images/emptyImg.jpg'>";
            } else {
                if (strstr($array['url'], "http") !== false) {
                    $r = "";
                } else {
                    $r = root;
                }
                $img = "<a target='_blank' href='" . $r . $array['url'] . "' title='点击查看大图'><img data-type='{$array['type']}' class='smallImg imgHover' src='" . $r . $array['url'] . "'></a>";
            }
            //打印本图像框
            $li .= "
			<li>
				" . $click . "
				<p>" . $array['title'] . "</p>
				<div>" . $img . "</div>
			</li>
			";
        }
        $html = <<<efo
		<div class='imgSingle'>
			<ul>{$li}</ul>
			<div class='clear'></div>
		</div>
		<div class='hidden'><form name="imgForm"><input type="hidden" name="mainId"><input type="hidden" name="type"><input name='ico' id='ico' type='file' onchange="uploadImgFile('imgForm',root+'control/adIndex.html?cla={$this->get('cla')}&fun=uploadIco','add-file-button')"></form></div>
		<script>
		//点击上传图片
        function clickUpload(id,type){
            $('[name=mainId]').val(id)
             $('[name=type]').val(type)
            $('#ico').click();
        }
        //上传图片
        function uploadImgFile(formName,url){
            let form = $("form[name='"+formName+"']")[0];
            let type= $('[name=type]').val();
            let formData = new FormData(form);
            $.ajax({
                type: "POST",
                contentType: false,
                processData: false,
                url: url,
                data: formData,
                cache: false,
                success: function (res) {
                    let result = JSON.parse(res);
                    $("[name='ico']").val('');
                    if (result.warn === 2) {
                        $("[data-type='"+type+"']").attr('src',result.data.src);
                    }else{
                        warn(result.warn)
                    }
                },
                error: function (e) {
                    console.log(e)
                    warn("上传失败");
                }
            });
        }
        </script>
efo;
        return $html;
    }

    /**
     *上传个人资料
     */
    function uploadIco(): bool|string
    {
        $type = $this->post('type');
        $info = query(self::table, " id = '{$this->post('id')}'");
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此人员';
        } else {
            $talentPool = new talentPoolClass();
            return $talentPool->saveIco(self::page, $info['id'], $type, $_FILES);
        }
        return json_encode($json, 320);
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'姓名',
                    'aliasName'=>'姓名',
                ],
                [
                    'columnName'=>'部门',
                    'aliasName'=>'部门',
                ],
                [
                    'columnName'=>'职位',
                    'aliasName'=>'职位',
                ],
                [
                    'columnName'=>'身份证号',
                    'aliasName'=>'身份证号',
                ],
                [
                    'columnName'=>'性别',
                    'aliasName'=>'性别',
                ],
                [
                    'columnName'=>'年龄',
                    'aliasName'=>'年龄',
                ],
                [
                    'columnName'=>'手机号',
                    'aliasName'=>'手机号',
                ],
                [
                    'columnName'=>'派遣日期',
                    'aliasName'=>'派遣日期',
                ],
                [
                    'columnName'=>'退回日期',
                    'aliasName'=>'退回日期',
                ],
                [
                    'columnName'=>'派遣单位',
                    'aliasName'=>'派遣单位',
                ],
                [
                    'columnName'=>'派遣协议编号',
                    'aliasName'=>'派遣协议编号',
                ],
                [
                    'columnName'=>'状态',
                    'aliasName'=>'状态',
                ],
            ]
        };
    }
}

